package org.luxor.commons.jdbc.metadata;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.annotation.JsonIgnore;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import org.luxor.commons.core.xss.SQLFilter;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Mr.Yan  @date 2019/9/26$
 */
@ApiModel(description = "分页查询")
public class PageQuery<T> implements Serializable {

    @ApiModelProperty(value = "当前页数", example = "1")
    private Long current = 1L;

    @ApiModelProperty(value = "每页记录数", example = "10")
    private Long size = 10L;

    @ApiModelProperty(value = "搜索条件", example = "{}")
    private T search;

    @ApiModelProperty(value = "排序条件", example = "[]")
    private List<OrderItem> orders;

    public PageQuery() {

    }

    @JsonIgnore
    public Page getPage() {
        Page pageParam = new Page(current, size);
        if (getOrders() != null) {
            List<com.baomidou.mybatisplus.core.metadata.OrderItem> orders = new ArrayList<com.baomidou.mybatisplus.core.metadata.OrderItem>();
            getOrders().forEach(order -> {
                        //防止SQL注入（因为column是通过拼接SQL实现的，会有SQL注入风险）
                        String column = SQLFilter.sqlInject(order.getColumn());
                        orders.add(new com.baomidou.mybatisplus.core.metadata.OrderItem().setColumn(column).setAsc(order.getAsc()));
                    }
            );
            pageParam.setOrders(orders);
        }
        return pageParam;
    }

    @JsonIgnore
    public QueryWrapper getQueryWrapper() {
        if (search == null) {
            return Wrappers.emptyWrapper();
        }
        return Wrappers.query(search);
    }

    public Long getCurrent() {
        return current;
    }

    public void setCurrent(Long current) {
        this.current = current;
    }

    public Long getSize() {
        return size;
    }

    public void setSize(Long size) {
        this.size = size;
    }

    public T getSearch() {
        return search;
    }

    public void setSearch(T search) {
        this.search = search;
    }

    public List<OrderItem> getOrders() {
        return orders;
    }

    public void setOrders(List<OrderItem> orders) {
        this.orders = orders;
    }
}
